!function (factory) {
    "use strict";
    "function" === typeof define && define.amd ? define(["jquery", "grid.locale-cn", "jquery.flot.resize"], factory) : factory(jQuery)
}(function ($) {

    var Grid = function (ele, opt) {

        var self = this;
        this.element = ele;
        // 默认分页获取url
        this.URL_GET_ALL_PAGE = '/get/all/page';
        // 默认修改url
        this.URL_POST_MODIFY = '/modify';
        this.defaults = $.extend({}, $.fn.jqGrid.defaults, {
            moduleKey: null,
            subGridOptions: {
                plusicon: 'ace-icon fa fa-plus center bigger-110 blue',
                minusicon: 'ace-icon fa fa-minus center bigger-110 blue',
                openicon: 'ace-icon fa fa-chevron-right center orange'
            },
            datatype: 'json',
            mtype: 'get',
            rownumbers: true,
            height: '100%',
            autowidth: true,
            width: 0,
            autoScroll: false,
            viewrecords: true,
            rowNum: 20,
            rowList: [20, 50, 100],
            altRows: true,
            multiselect: false,
            //multikey: "ctrlKey",
            multiboxonly: true,
            emptyrecords: '没有记录',
            navbarDefaultIcon: {},
            loadComplete: function () {
                setTimeout(function () {
                    self.styleCheckbox(ele);
                    self.updateActionIcons(ele);
                    self.updatePagerIcons(ele);
                    self.enableTooltips(ele);
                }, 0);
            }
        });
        this.navbarDefaultIcon = $.extend({}, {
            edit: true,
            editicon: 'ace-icon fa fa-pencil blue',
            add: true,
            addicon: 'ace-icon fa fa-plus-circle purple',
            del: true,
            delicon: 'ace-icon fa fa-trash-o red',
            search: false,
            searchicon: 'ace-icon fa fa-search orange',
            refresh: true,
            refreshicon: 'ace-icon fa fa-refresh green',
            view: true,
            viewicon: 'ace-icon fa fa-search-plus grey'
        }, opt.navbarDefaultIcon || {});
        this.options = $.extend({}, this.defaults, opt || {});

    };
    Grid.prototype = {
        init: function () {

            var $element = $(this.element);
            // 判断是否有moduleKey，有的话设置自动设置url与editurl
            if (this.options.moduleKey) {
                if (!this.options.url || this.options.url.trim() === '') {
                    this.options.url = '/' + this.options.moduleKey + this.URL_GET_ALL_PAGE;
                }
                if (!this.options.editurl || this.options.editurl.trim() === '') {
                    this.options.editurl = '/' + this.options.moduleKey + this.URL_POST_MODIFY;
                }
            }
            // 初始化表格
            $element.jqGrid(this.options);
            // 添加序号列名
            // $element.jqGrid('setLabel', 'rn', '序号', {'text-align': 'center'}, '');
            // 导航按钮
            $element.jqGrid('navGrid', this.options.pager, this.navbarDefaultIcon,
                this.navEdit(),
                this.navAdd(),
                this.navDel(),
                this.navSearch(),
                this.navView());
            // this.layout();
        },
        /**
         * 布局
         */
        layout: function () {

            var $element = $(this.element);
            var parent_column = $element.closest('[class*="col-"]');
            var REDUCE_HEIGHT = 340;
            // 调整大小以适合页面大小
            parent_column.on('resize', function () {
                $element.jqGrid('setGridWidth', parent_column.width());
            });
            //自应高度
            $(window).resize(function () {
                $element.setGridHeight($(window).height() - REDUCE_HEIGHT);
            });
            // 在侧边栏上调整大小折叠/展开
            $(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
                if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
                    // setTimeout仅适用于webkit，为DOM更改提供时间，然后重绘！
                    setTimeout(function () {
                        $element.jqGrid('setGridWidth', parent_column.width());
                    }, 20);
                }
            });
            // 触发器窗口调整大小以使网格获得正确的大小
            $(window).triggerHandler('resize.jqGrid');
            $element.setGridHeight($(window).height() - REDUCE_HEIGHT);
        },
        /**
         * 按钮编辑
         */
        navEdit: function () {

            var self = this;
            var $element = $(self.element);
            return {
                // 编辑
                recreateForm: true,
                beforeShowForm: function (e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
                        .wrapInner('<div style="background: rgb(67, 142, 185); color: white;" class="widget-header" />')
                        .find('a').css('color', 'white');
                    self.style_edit_form(form);
                    self._addHiddenControl.apply(self.element, [form, self.options.colModel]);
                    self.afterShowFormCenter();
                },
                afterComplete: function (data, postData) {
                    // 显示请求返回信息
                    $.xumf.gritterError(data.responseJSON.msg);
                    // 触发事件
                    $.Event('xumf_gird.edit.afterComplete', {relatedTarget: $element[0]});
                    $element.trigger('xumf_gird.edit.afterComplete', [data, postData]);
                }
            };
        },
        /**
         * 按钮添加
         */
        navAdd: function () {

            var self = this;
            var $element = $(self.element);
            return {
                // 新增界面
                closeAfterAdd: true,
                recreateForm: true,
                viewPagerButtons: false,
                beforeShowForm: function (e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
                        .wrapInner('<div style="background: rgb(67, 142, 185); color: white;" class="widget-header" />')
                        .find('a').css('color', 'white');
                    self.style_edit_form(form);
                    self._addHiddenControl.apply(self.element, [form, self.options.colModel]);
                    self.afterShowFormCenter();
                },
                onclickSubmit: function (params, postData) {
                    // 避免id为null
                    postData.id = 0;
                    return postData;
                },
                afterComplete: function (data, postData) {
                    // 错误时，显示请求返回信息
                    !data.responseJSON.success && $.xumf.gritterError(data.responseJSON.msg);
                    // 触发事件
                    $.Event('xumf_gird.add.afterComplete', {relatedTarget: $element[0]});
                    $element.trigger('xumf_gird.add.afterComplete', [data, postData]);
                }
            };
        },
        /**
         * 按钮删除
         */
        navDel: function () {

            var self = this;
            var $element = $(self.element);
            return {
                // 删除界面
                recreateForm: true,
                beforeShowForm: function (e) {
                    var form = $(e[0]);
                    if (form.data('styled')) return false;
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
                        .wrapInner('<div style="background: rgb(67, 142, 185); color: white;" class="widget-header" />')
                        .find('a').css('color', 'white');
                    self.style_delete_form(form);
                    form.data('styled', true);
                    self.afterShowFormCenter();
                },
                afterSubmit: function (data, postData) {
                    // alert("afterSubmit");
                    return [true, ""]; //返回0表示正常
                },
                afterComplete: function (data, postData) {
                    // 显示请求返回信息
                    $.xumf.gritterError(data.responseJSON.msg);
                    // 触发事件
                    $.Event('xumf_gird.delete.afterComplete', {relatedTarget: $element[0]});
                    $element.trigger('xumf_gird.delete.afterComplete', [data, postData]);
                }
            };
        },
        /**
         * 按钮搜索
         */
        navSearch: function () {
            var self = this;
            return {
                // 搜索界面
                recreateForm: true,
                afterShowSearch: function (e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
                        .wrapInner('<div style="background: rgb(67, 142, 185); color: white;" class="widget-header" />')
                        .find('a').css('color', 'white');
                    self.style_search_form(form);
                    self.afterShowFormCenter();
                },
                afterRedraw: function () {
                    self.style_search_filters($(this));
                },
                afterComplete: function (data, postdata) {
                    // 显示请求返回信息
                    $.xumf.gritterError(data.responseJSON.msg);
                },
                multipleSearch: true
                /**
                 multipleGroup:true,
                 showQuery: true
                 */
            };
        },
        /**
         * 按钮查看
         */
        navView: function () {
            var self = this;
            return {
                // 查看界面
                recreateForm: true,
                beforeShowForm: function (e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
                        .wrapInner('<div style="background: rgb(67, 142, 185); color: white;" class="widget-header" />')
                        .find('a').css('color', 'white');
                    self.afterShowFormCenter()
                }
            };
        },
        // 重新加载或导航网格时会导致一些闪烁
        // 可能有一些自定义格式化程序来执行此操作，因为正在创建网格以防止这种情况
        // 或返回网格的默认浏览器复选框样式
        styleCheckbox: function (table) {
            $(table).find('input:checkbox').addClass('ace')
                .wrap('<label />')
                .after('<span class="lbl align-top" />');
            $('.ui-jqgrid-labels th[id*="_cb"]:first-child')
                .find('input.cbox[type=checkbox]').addClass('ace')
                .wrap('<label />').after('<span class="lbl align-top" />');
        },
        // 与navButtons图标不同，行中的动作图标似乎是硬编码的
        // 如果你愿意的话，你可以在这里改变它们
        updateActionIcons: function (table) {
            var replacement =
                {
                    'ui-ace-icon fa fa-pencil': 'ace-icon fa fa-pencil blue',
                    'ui-ace-icon fa fa-trash-o': 'ace-icon fa fa-trash-o red',
                    'ui-icon-disk': 'ace-icon fa fa-check green',
                    'ui-icon-cancel': 'ace-icon fa fa-times red'
                };
            $(table).find('.ui-pg-div span.ui-icon').each(function () {
                var icon = $(this);
                var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
                if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
            })
        },
        // 用上面的FontAwesome图标替换图标
        updatePagerIcons: function (table) {
            var replacement =
                {
                    'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
                    'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
                    'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
                    'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
                };
            $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
                var icon = $(this);
                var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

                if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
            })
        },
        // 移动到按钮的提示
        enableTooltips: function (table) {
            $('.navtable .ui-pg-button').tooltip({container: 'body'});
            $(table).find('.ui-pg-div').tooltip({container: 'body'});
        },
        // 居中dialog
        afterShowFormCenter: function () {
            var winWidth = $(window).width();
            var $ui = $('.ui-jqdialog');
            var divWidth = $ui.width();
            var left = (winWidth - divWidth) / 2;
            $ui.css({left: left});
        },
        style_edit_form: function (form) {
            // 在“date”字段中启用datepicker
            form.find('input[type=date]').datepicker({format: 'yyyy-mm-dd', autoclose: true});

            form.find('input[type=checkbox]').addClass('ace ace-switch ace-switch-5').after('<span class="lbl"></span>');
            // 不要在label元素内包装，不会提交复选框值（POST'ed）
            // .addClass（'ace ace-switch ace-switch-5'）。wrap（'<label class =“inline”/>').after('<span class =“lbl”> </ span>'）;
            //更新按钮类
            var buttons = form.next().find('.EditButton .fm-button');
            buttons.addClass('btn btn-sm').find('[class*="-icon"]').hide();//ui-icon, s-icon
            buttons.eq(0).addClass('btn-primary').prepend('<i class="ace-icon fa fa-check"></i>');
            buttons.eq(1).prepend('<i class="ace-icon fa fa-times"></i>');

            buttons = form.next().find('.navButton a');
            buttons.find('.ui-icon').hide();
            buttons.eq(0).append('<i class="ace-icon fa fa-chevron-left"></i>');
            buttons.eq(1).append('<i class="ace-icon fa fa-chevron-right"></i>');
        },
        style_delete_form: function (form) {
            var buttons = form.next().find('.EditButton .fm-button');
            buttons.addClass('btn btn-sm').find('[class*="-icon"]').hide();//ui-icon, s-icon
            buttons.eq(0).addClass('btn-danger').prepend('<i class="ace-icon fa fa-check"></i>');
            buttons.eq(1).prepend('<i class="ace-icon fa fa-times"></i>');
        },
        style_search_filters: function (form) {
            form.find('.delete-rule').val('X');
            form.find('.add-rule').addClass('btn btn-xs btn-primary');
            form.find('.add-group').addClass('btn btn-xs btn-success');
            form.find('.delete-group').addClass('btn btn-xs btn-danger');
        },
        style_search_form: function (form) {
            var dialog = form.closest('.ui-jqdialog');
            var buttons = dialog.find('.EditTable');
            buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'ace-icon fa fa-retweet');
            buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'ace-icon fa fa-comment-o');
            buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'ace-icon fa fa-search');
        },
        // 添加隐藏input
        _addHiddenControl: function ($form, colModel) {
            var self = this;
            colModel.forEach(function (value) {
                $.isFunction(value.addHiddenControl)
                && $form.find('*[id={{name}}]'.replace(/{{name}}/, value.name)).val(value.addHiddenControl.call(self));
            });
        }
    };

    $.fn.xumfJqGird = $.fn.xumf_jqGird = function (options) {

        // 判断是否为方法
        if ("string" === typeof options) {
            // 获取方法
            var method = $.jgrid.getMethod(options);
            // 判断方法存不存在
            if (!method) throw"jqGrid - 没有这样的方法: " + options;
            // 获取参数
            var args = $.makeArray(arguments).slice(1);
            // 执行方法
            return method.apply(this, args)
        }
        return this.each(function () {
            var grid = new Grid(this, options);
            grid.init();
            grid.layout();
        })
    };

    /**
     * 获取jqgrid 当前选择行
     * @param callback 回调
     */
    $.fn.getGridSelectedRow = function (callback) {
        var rowId = this.xumf_jqGird('getGridParam', 'selrow');
        if (null === rowId) {
            $.xumf.gritterError('请选择行');
        } else {
            var rowData = this.xumf_jqGird('getRowData', rowId);
            $.isFunction(callback) && callback(rowData);
        }
        return this;
    }

});